package com.znxs.bs_c.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Quarter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.znxs.bs_c.common.Result;
import com.znxs.bs_c.common.Status;
import com.znxs.bs_c.entity.dto.UserDTO;
import com.znxs.bs_c.service.IRoleService;
import com.znxs.bs_c.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.znxs.bs_c.service.IUserService;
import com.znxs.bs_c.entity.User;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 左拿
 * @since 2023-08-15
 */
@RestController
@RequestMapping("/user") // http://localhost:8888/user
public class UserController {
    @Resource
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    // 【数据可视化】获取各个季度会员的数量
    @GetMapping("/members")
    public Result getMembersCountByQuarter(){
        List<User> list = userService.list();
        int q1 = 0;
        int q2 = 0;
        int q3 = 0;
        int q4 = 0;
        for (User user :list) {
            Quarter quarter = DateUtil.quarterEnum(user.getCreateTime());
            switch (quarter){
                case Q1:q1++;break;
                case Q2:q2++;break;
                case Q3:q3++;break;
                case Q4:q4++;break;
            }
        }
        Map<String, Object> memberData = new HashMap<>();
        memberData.put("第一季度",q1);
        memberData.put("第二季度",q2);
        memberData.put("第三季度",q3);
        memberData.put("第四季度",q4);
        return Result.success(memberData);
    }

    // 登录接口
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(400, Status.ParamsError.getMessage());
        }
        UserDTO userdto = userService.login(userDTO);
        return Result.success(userdto);
    }

    // 注册接口
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        System.out.println(username + "," + password);
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(400, Status.ParamsError.getMessage());
        }
        return Result.success(userService.register(userDTO));
    }


    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody User user) {
        return Result.success(userService.saveOrUpdate(user));
    }

    // 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        return Result.success(userService.removeById(id));
    }

    // 根据id批量删除
    @DeleteMapping
    public Result deleteByIds(@RequestBody List<Integer> Ids) {
        return Result.success(userService.removeByIds(Ids));
    }

    // 查询所有
    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    // 根据id查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable("id") Integer id) {
        return Result.success(userService.getById(id));
    }

    // 根据用户名查询
    @GetMapping("/person/{username}")
    public Result findOne(@PathVariable("username") String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        return Result.success(userService.getOne(userQueryWrapper));
    }

    // 分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam("current") Integer current,
                           @RequestParam("pageSize") Integer pageSize,
                           @RequestParam(value = "username", required = false) String username,
                           @RequestParam(value = "email", required = false) String email,
                           @RequestParam(value = "address", required = false) String address
    ) {
        IPage<User> page = new Page<>(current, pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("username", username).like("email", email).like("address", address);
        userQueryWrapper.orderByDesc("id");
        return Result.success(userService.page(page, userQueryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查到所有的数据
        List<User> userList = userService.list();
        // 通过工具类创建writer 写出磁盘路径

        // 内存操作 写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");

        // 一次性写出userList 内的对象到excel 内 使用默认样式，强制输出标题
        writer.write(userList, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // 设置显示编码格式
        String fileName = new String("用户信息".getBytes("utf-8"), "ISO8859-1");
        // 设置响应头
        response.setHeader("Content-Disposition",
                String.format("attachment;fileName=%s%s",fileName,".xlsx") );

        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 刷新write 的内容到输出流去
        writer.flush(outputStream, true);
        // 关闭流
        outputStream.close();
        writer.close();
    }

    // 导入
    @PostMapping("/import")
    public void imp(@RequestParam MultipartFile file) throws Exception {
        // 获取输入流
        InputStream inputStream = file.getInputStream();
        // ExcelUtil设置数据
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 设置别名
        reader.addHeaderAlias("用户名", "username");
        reader.addHeaderAlias("密码", "password");
        reader.addHeaderAlias("昵称", "nickname");
        reader.addHeaderAlias("邮箱", "email");
        reader.addHeaderAlias("电话", "phone");
        reader.addHeaderAlias("地址", "address");
        reader.addHeaderAlias("创建时间", "createTime");
        reader.addHeaderAlias("头像", "avatarUrl");
        // 读取数据
        List<User> userList = reader.readAll(User.class);
        // 存入数据
        userService.saveBatch(userList);
    }

}

